package com.pur.zsms.matermanage.mater.web;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pur.zsms.accountmanage.vo.AccountVo;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.filter.AttributeListenerUtil;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.ApplicationUtil;
import com.pur.zsms.matermanage.mater.po.MaterPo;
import com.pur.zsms.matermanage.mater.po.UnitMaterConvertPo;
import com.pur.zsms.matermanage.mater.service.IMaterCheckService;
import com.pur.zsms.matermanage.mater.service.IMaterService;
import com.pur.zsms.matermanage.mater.vo.MaterValueVo;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.matermanage.mater.vo.MaterVoForUnit;
import com.pur.zsms.matermanage.mater.vo.ShoppingCartMaterVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.systemsetting.datadictionary.service.IDataDictionaryService;

@Controller
@RequestMapping(value = "/materUnit")
public class MaterUnitControllor {

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(MaterUnitControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "materService")
	private IMaterService materService;

	@Resource(name = "shopService")
	private IShopService shopService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "dictionaryService")
	private IDataDictionaryService dataDictionaryService;

	@Resource(name = "materCheckService")
	private IMaterCheckService materCheckService;

	@RequestMapping(value = "/findMaterUnit.do", method = { RequestMethod.POST })
	@ResponseBody
	public String findMaterUnit(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			MaterVoForUnit materVoForUnit, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));

		UserPo userInfo = (UserPo) session.getAttribute("user");
		materVoForUnit.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		this.pageList = materService.listMaterUnit(pageController, materVoForUnit);
		List<MaterVoForUnit> materList = new ArrayList<MaterVoForUnit>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				MaterVoForUnit f = new MaterVoForUnit();
				f.setMaterId((Integer) item[0]);
				f.setMaterName((String) item[1]);
				f.setMaterType((Integer) item[2]);
				f.setMaterLevel((Integer) item[3]);
				f.setMaterValue(((BigDecimal) item[4]).multiply(new BigDecimal("1000")));
				f.setMaterProportion((Integer) item[5]);
				f.setMaterDescribe((String) item[6]);
				f.setSupId((Integer) item[7]);
				f.setSupName((String) item[8]);

				f.setMaterValueUndressed(((BigDecimal) item[9]).multiply(new BigDecimal("1000")));

				f.setUnit((String) item[10]);
				f.setSpecifications((String) item[11]);
				f.setBrands((String) item[12]);
				f.setDeleteFlag((Integer) item[13]);

				f.setHostMaterIdFlag(1);

				materList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", materList);
		return json.toString();
	}

	@RequestMapping(value = "/preAddMaterUnit.do", method = { RequestMethod.GET })
	public ModelAndView preAddMaterUnit(HttpSession session) {
		Map map = new HashMap();
		// map.put("rolelist", roleList);
		return new ModelAndView("/matermanage/materUnit/addMaterUnit", map);
	}

	@RequestMapping(value = "/addMaterUnit.do", method = { RequestMethod.POST })
	@ResponseBody
	public String addMaterUnit(MaterVoForUnit c, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			c.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
			boolean flag = materService.addMaterUnit(c);
			if (flag) {
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("msg", materService.getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	@RequestMapping(value = "/getHostMaterUnit.do", method = { RequestMethod.POST })
	@ResponseBody
	public String getHostMaterUnit(HttpSession session, HttpServletRequest request, HttpServletResponse response, int materId) {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		boolean flag = true;
		try {
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			UnitMaterConvertPo tUnitMaterConvertPo = materCheckService.checkHostMaterUnit(supId, materId);
			if (tUnitMaterConvertPo == null) {
				json.put("success", false);
				return json.toString();
			} else {
				MaterPo tmaterPo = materService.getMaterPo(tUnitMaterConvertPo.getHostMaterId());
				json.put("success", true);
				json.put("materPo", tmaterPo);
			}
		} catch (GenericException e) {
			e.printStackTrace();
			json.put("success", false);
			return json.toString();
		}
		return json.toString();
	}

	@RequestMapping(value = "/deleteMaterUnitHostMaterId.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteMaterUnitHostMaterId(HttpSession session, int hostMaterId) {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			materService.deleteMaterUnitHostMaterId(hostMaterId, supId);
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/deleteMaterUnitAuxiliaryMaterId.do", method = { RequestMethod.POST })
	@ResponseBody
	public String deleteMaterUnitAuxiliaryMaterId(HttpSession session, int auxiliaryMaterId) {
		JSONObject json = new JSONObject();
		UserPo userInfo = (UserPo) session.getAttribute("user");
		try {
			int supId = supplierService.getSupIdByUserId(userInfo.getUserId());
			materService.deleteMaterUnitAuxiliaryMaterId(auxiliaryMaterId, supId);
			json.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
			json.put("msg", e.getMessage());
		}
		return json.toString();
	}

	@RequestMapping(value = "/preLookMaterUnitByHostMaterId.do", method = { RequestMethod.GET })
	public ModelAndView preLookMaterUnitByHostMaterId(int hostMaterId) {
		Map map = new HashMap();

		try {
			MaterPo materPo = materService.getMaterPo(hostMaterId);
			map.put("materName", hostMaterId + ":" + materPo.getMaterName() + "-单位：" + materPo.getUnit());
			map.put("materId", hostMaterId);
		} catch (GenericException e) {
			e.printStackTrace();
		}

		return new ModelAndView("/matermanage/materUnit/lookMaterUnit", map);
	}

	@RequestMapping(value = "/preLookMaterUnitByAuxiliaryMaterId.do", method = { RequestMethod.GET })
	public ModelAndView preLookMaterUnitByAuxiliaryMaterId(int auxiliaryMaterId, HttpSession session) {
		Map map = new HashMap();
		try {
			UserPo userInfo = (UserPo) session.getAttribute("user");
			UnitMaterConvertPo tUnitMaterConvertPo = materCheckService.getUnitMaterConvertPoByAuxiliaryMaterId(
					supplierService.getSupIdByUserId(userInfo.getUserId()), auxiliaryMaterId);

			MaterPo materPo = materService.getMaterPo(tUnitMaterConvertPo.getHostMaterId());
			map.put("materName", tUnitMaterConvertPo.getHostMaterId() + ":" + materPo.getMaterName() + "-单位：" + materPo.getUnit());
			map.put("materId", tUnitMaterConvertPo.getHostMaterId());
		} catch (GenericException e) {
			e.printStackTrace();
		}

		return new ModelAndView("/matermanage/materUnit/lookMaterUnit", map);
	}

	@RequestMapping(value = "/lookMaterUnit.do", method = { RequestMethod.POST })
	@ResponseBody
	public String lookMaterUnit(@RequestParam(required = false) String page, @RequestParam(required = false) String rows,
			MaterVoForUnit materVoForUnit, HttpSession session) throws GenericException {
		JSONObject json = new JSONObject();
		if (page == null || page.equals(""))
			page = "1";
		if (rows == null || rows.equals(""))
			rows = "10";
		PageController pageController = new PageController(Integer.parseInt(page), Integer.parseInt(rows));

		UserPo userInfo = (UserPo) session.getAttribute("user");
		materVoForUnit.setSupId(supplierService.getSupIdByUserId(userInfo.getUserId()));
		this.pageList = materService.lookMaterUnit(pageController, materVoForUnit);
		List<MaterVoForUnit> materList = new ArrayList<MaterVoForUnit>();
		List items = pageList.getItems();
		if (items != null) {
			for (int i = 0; i < items.size(); i++) {
				Object[] item = (Object[]) items.get(i);
				MaterVoForUnit f = new MaterVoForUnit();
				f.setMaterId((Integer) item[0]);
				f.setMaterName((String) item[1]);
				f.setMaterType((Integer) item[2]);
				f.setUnit((String) item[3]);
				f.setSpecifications((String) item[4]);
				f.setBrands((String) item[5]);
				materList.add(f);
			}
		}
		json.put("success", true);
		json.put("total", pageList.getTotalCount());
		json.put("rows", materList);
		log.info("----" + json.toString());
		return json.toString();
	}
}
